//
//  SettingViewController.m
//  FKGW
//
//  Created by song ce on 2017/2/17.
//  Copyright © 2017年 song ce. All rights reserved.
//

#import "SettingViewController.h"
#import "PhoneViewController.h"
#import "SignViewController.h"
#import "AboutViewController.h"
#import "ManagerLoctaionViewController.h"
#import "PwdViewController.h"
#import "SexViewController.h"
#import "UserViewController.h"
#import "FirstSetPwdViewController.h"
#import <Hyphenate/Hyphenate.h>
#import "BaseImagePickerController.h"
#import "OSSHelper.h"
@interface SettingViewController ()<UIActionSheetDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property(nonatomic,strong)NSDictionary *dataDic;
@end

@implementation SettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.vcName = @"设置";
    self.imageName = @"icon_toxiang_yidenglu";
    NSString *image_Name=  [[NSUserDefaults standardUserDefaults]objectForKey:USERID];
    if(image_Name.length){
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                             NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString* path1 = [documentsDirectory stringByAppendingPathComponent:image_Name];
        self.imageName = path1;
    }
    [self loadDataSource];
   
//    self.isNeedMessageItem = YES;
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeAvater) name:@"changeAvater" object:nil];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //获取数据源
    [self loadData];
}
//修改头像
-(void)changeAvater{
    DLog(@"修改头像");
    UIActionSheet *s = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相册", @"相机", nil];
    [s showInView:self.view];
}
#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    DLog(@"%zd",buttonIndex);
    if (buttonIndex == 2) {
        [actionSheet dismissWithClickedButtonIndex:2 animated:YES];
        return;
    }
    UIImagePickerControllerSourceType sourceType;
    if (buttonIndex == 0) {
        //获取本地图片
        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    if (buttonIndex == 1) {
        //判断当前设备是否有摄像头
        BOOL isCamera = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
        if (!isCamera) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前没有摄像头可以使用" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
            return;
        }
        if ([BaseImagePickerController isCameraValid]) {
            //使用相机
            sourceType = UIImagePickerControllerSourceTypeCamera;
        }
    }
    BaseImagePickerController *imgPicker = [[BaseImagePickerController alloc] init];
    imgPicker.sourceType = sourceType;
    imgPicker.delegate = self;
//    imgPicker.allowsEditing = YES;
    [self presentViewController:imgPicker animated:YES completion:nil];
}
#pragma mark -UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    //获取选取的图片
    DLog(@"获取选取的图片info-----%@",info);
    UIImage *image=info[UIImagePickerControllerOriginalImage];
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        //将图片写到本地
        UIImageWriteToSavedPhotosAlbum(image, self , @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }else if(picker.sourceType==UIImagePickerControllerSourceTypePhotoLibrary){
        //上传头像
        [self uploadImage:image];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}
//图片保存成功后调用的方法
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    DLog(@"通过拍照获取的头像保存成功");
    //上传头像
    [self uploadImage:image];
}

//上传头像
-(void)uploadImage:(UIImage*)image{
     [MBProgressHUD showActivityMessageInWindow:@"正在上传头像..."];
    NSString *path = @"user/header";
    __weak typeof(self) weakSelf = self;
    [[OSSHelper sharedHelper]OSSUploadImageWithImage:image path:path resultBlock:^(NSString *objectKey) {
        DLog(@"objectKey---%@",objectKey);
        NSArray  *strArr = [objectKey componentsSeparatedByString:@"/"];
        if(strArr.count){
            objectKey =  strArr.lastObject;
        }
        //向服务器提交
        NSDictionary *paramDic =
                                                    @{@"userId":USERID,
                                                         @"url":objectKey};
        [Tools AFNetworkingRequestTypePostWithUrl:CHANGEPHOTO paramters:paramDic afterResultBlock:^(NSDictionary *resultDic) {
            DLog(@"--提交头像url--%@",resultDic);
            if([resultDic[@"flag"] isEqualToString:@"true"]){
                NSDictionary *dic = resultDic[@"data"];
                if([dic isKindOfClass:[NSNull class]]) return ;
                if([dic[@"status"] isEqualToString:@"true"]){
                    [MBProgressHUD dismiss];
                    [MBProgressHUD showSuccessMessage:@"头像修改成功"];
                    [weakSelf saveTolocal:image];
                }else{
                    [MBProgressHUD dismiss];
                    if(dic[@"errorString"]){
                        [MBProgressHUD showTipMessageInWindow:dic[@"errorString"]];
                    }
                }
            }else{
                [MBProgressHUD dismiss];
                if(resultDic[@"errorString"]){
                    [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
                }
            }
        }];
    }];
}

-(void)saveTolocal:(UIImage*)image{
    NSString *imageName;
    NSData *imageData = UIImageJPEGRepresentation(image, 1);
    imageName = [NSString stringWithFormat:@"%@.jpg",USERID];
    if(imageData.length>1024*1024){
        imageData = UIImageJPEGRepresentation(image, .1);
        DLog(@"--2--%zd",imageData.length/1024);
    }
    //本地头像路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString* path = [documentsDirectory stringByAppendingPathComponent:imageName];
    BOOL isSuccess = [imageData writeToFile:path atomically:YES];
    if(isSuccess){
        //保存本地头像的路径
        [[NSUserDefaults standardUserDefaults]setObject:imageName forKey:USERID];
        [[NSUserDefaults standardUserDefaults]synchronize];
        DLog(@"本地保存路径---%@",path);
        //通知登录页面切换头像
        [[NSNotificationCenter defaultCenter]postNotificationName:@"changePhoto" object:nil];
        self.imageName = path;
        [self loadDataSource];
    }
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
-(void)rightAction{
    
    
}

//退出登录 复写父类中的退出登录方法
- (void)logOutAction{
    //异步退出环信登录
     [[EMClient sharedClient]  logout:YES completion:^(EMError *aError) {
         if (!aError) {
             // 退出登录成功之后  不能再设置自动登录
             [[EMClient sharedClient].options setIsAutoLogin:NO];
             DLog(@"退出环信成功");
         } else {
             DLog(@"退出环信失败");
         }
     }];
    [MBProgressHUD showTipMessageInWindow:@"退出登录成功"];
    [AppDelegate appDealegate].uid = @"";
    NSUserDefaults *useDefault = [NSUserDefaults standardUserDefaults];
    [useDefault removeObjectForKey:@"userId"];
    [useDefault synchronize];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"logOutSuccess" object:nil];
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)loadData{
    //2.46查看设置信息
    NSDictionary *paraDic = @{
                              @"userId":USERID,
                              };
    __weak typeof(self)  weakSelf = self;
    [Tools AFNetworkingRequestTypePostWithUrl:CONFIGMESSAGE paramters:paraDic  afterResultBlock:^(NSDictionary *resultDic) {
         DLog(@"查看设置信息--%@",resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSDictionary *dataDic =resultDic[@"data"];
            if([dataDic isKindOfClass:[NSNull class]]) return ;
            weakSelf.dataDic =dataDic;
            [weakSelf loadDataSource];
            //加载头像
            NSString *userPhoto = resultDic[@"userPhoto"];
            if([userPhoto isKindOfClass:[NSNull class]]){
                userPhoto = @"";
            }
            [weakSelf loadPhoto:userPhoto];
        }
    }];
}

-(void)loadPhoto:(NSString*)path{
    NSString *image_Name=  [[NSUserDefaults standardUserDefaults]objectForKey:USERID];
    if(!image_Name.length&&path.length){
        __weak typeof(self) weakSelf = self;
//         path = [NSString stringWithFormat:@"user/header/%@%@",USERID,@".jpg"];
        [[OSSHelper sharedHelper] OSSDownLoadWithObjectKey:path downLoadBlock:^(NSData *data) {
            UIImage *iamge = [UIImage imageWithData:data];
            [weakSelf saveTolocal:iamge];
        }];
    }
}

#pragma mark - PublicMethods
- (void)loadDataSource {
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *sex;
        NSString *userName;
        NSString *userPhone;
        NSString *signature;
        if(![weakSelf.dataDic isKindOfClass:[NSNull class]]){
            sex = weakSelf.dataDic[@"sex"];
            userName = weakSelf.dataDic[@"nickName"];
            userPhone = weakSelf.dataDic[@"userPhone"];
            signature = weakSelf.dataDic[@"Signature"];
            [AppDelegate appDealegate].huanxinUserName =weakSelf.dataDic[@"userName"];
        }
        if([sex isKindOfClass:[NSNull class]]){
            sex = @"";
        }
        if([userName isKindOfClass:[NSNull class]]){
            userName = @"";
        }
        if([userPhone isKindOfClass:[NSNull class]]){
            userPhone = @"";
        }
        if([signature isKindOfClass:[NSNull class]]){
            signature = @"";
            [AppDelegate appDealegate].isFirstSetSignature = YES;
        }
        USERPHONE = userPhone;
        USERNAME = userName;
        USERSEX = sex;
        USERSIGNATURE = signature;
        
        //第一组
        SettingItem *settingItem1 = [RightImageSettingItem rightImageItemWithTitle:@"头像" imageName:weakSelf. imageName];
        SettingItem *settingItem2 = [IndicatorSettingItem indicatorItemWithTitle:@"用户名" destVcClass:[UserViewController class] vcTitle:@"用户名" rightTitle:userName isRightTitle:YES];
        SettingItem *settingItem3 = [IndicatorSettingItem indicatorItemWithTitle:@"个性签名" destVcClass:[SignViewController class] vcTitle:@"个性签名" rightTitle:signature isRightTitle:YES];
        SettingItem *settingItem4 = [IndicatorSettingItem indicatorItemWithTitle:@"性别" destVcClass:[SexViewController class] vcTitle:@"性别" rightTitle:sex isRightTitle:YES];
        SettingGroup *group0 = [[SettingGroup alloc]init];
        group0.items = @[settingItem1,settingItem2,settingItem3,settingItem4];
        
        //第二组
        SettingItem *settingItem01 = [IndicatorSettingItem indicatorItemWithTitle:@"绑定手机号" destVcClass:[PhoneViewController class] vcTitle:@"更改绑定手机号" rightTitle:userPhone isRightTitle:YES];
        SettingItem *settingItem02= [IndicatorSettingItem indicatorItemWithTitle:@"修改密码" destVcClass:[PwdViewController class] vcTitle:@"修改密码"];
//         SettingItem *settingItem03= [IndicatorSettingItem indicatorItemWithTitle:@"管理收获地址" destVcClass:[ManagerLoctaionViewController class] vcTitle:@"管理收获地址"];
         SettingItem *settingItem04= [IndicatorSettingItem indicatorItemWithTitle:@"关于我们" destVcClass:[AboutViewController class] vcTitle:@"关于我们"];
        SettingGroup *group1 = [[SettingGroup alloc]init];
//        group1.items = @[settingItem01,settingItem02,settingItem03,settingItem04];
          group1.items = @[settingItem01,settingItem02,settingItem04];

        NSMutableArray *dataSource = [[NSMutableArray alloc] initWithObjects:
                                      group0,
                                      group1,
//                                      group2,
                                      nil];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.dataSource = dataSource;
            [self.tableView reloadData];
        });
    });
}




@end
